package Services;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.util.ArrayList;
import java.util.List;
import javaBeans.Film;
import java.util.Date;

public class GetFilmService {

	TwoDPService twoDecimalService = new TwoDPService();
	List<Film> filmList = new ArrayList<Film>();
	CallableStatement cs;
	Statement stmt;
	DBConnection connection = new DBConnection();
	Connection con = connection.getConnection();
	ResultSet rs;

	public List<Film> getFilms() {
		return getFilms(null, null);
	}

	public List<Film> getFilms(Film film) {

		if ((String) film.getGenre() != "" && (String) film.getName() != "") {
			return getFilms((String) film.getName(), (String) film.getGenre());
		} else if ((String) film.getGenre() != ""
				&& (String) film.getName() == "") {
			return getFilms(null, (String) film.getGenre());
		} else if ((String) film.getGenre() == ""
				&& (String) film.getName() != "") {
			return getFilms((String) film.getName(), null);
		} else {
			return getFilms(null, null);
		}
	}

	public List<Film> getFilms(String name, String genre) {
		try {
			cs = con.prepareCall("{call searchfilm(?,?)}");

			if (name == null) {
				cs.setNull(1, java.sql.Types.NULL);
			} else {
				cs.setString(1, name);
			}

			if (genre == null) {
				cs.setNull(2, java.sql.Types.NULL);
			} else {
				cs.setString(2, genre);
			}
			rs = cs.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			while (rs.next()) {
				int idFilm = rs.getInt("idfilm");
				String rname = rs.getString("name");
				String rgenre = rs.getString("genre");
				String description = rs.getString("description");
				String userWhoAdded = rs.getString("username");
				Date dateAdded = rs.getDate("timestamp");
				Double rating = rs.getDouble("rating");
				int numvotes = rs.getInt("numvotes");
				rating = twoDecimalService.roundTwoDecimal(rating);
				Film film = new Film(idFilm, rname, rgenre, description,
						dateAdded, userWhoAdded, rating, numvotes);
				filmList.add(film);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return filmList;
	}

}
